#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Charles.chen
# createDate:2017/9/4
# Title:
# Tip:
from peewee import *
from app.toolkit import commonUtil
from flask_login import UserMixin
from app import login_manager
from app.toolkit.configSingle import ConfigSingle

# db file path
db = SqliteDatabase('./iot-x.db')
configObj = ConfigSingle()

def initDb():
    # db.create_tables([User, Dust, SensorData, SystemInfo, Sensor, RemoteCommand], safe=True)
    db.create_tables([User, SensorData, Sensor, FileManager, Dust], safe=True)
    User.createdDefaultAccount()
    db.close()

class BaseModel(Model):
    class Meta:
        database = db

# 用户信息模型
class User(UserMixin, BaseModel):
    id = IntegerField(primary_key=True)
    account = CharField(max_length=20)
    pwd = CharField(max_length=200)
    pwd_hash = CharField(max_length=200)
    created_time = DateField()

    @staticmethod
    def getUserByAccountAndPwd(account, pwd):
        user_instance = User()
        # pwd_hash = generate_password_hash(pwd)
        try:
            user = user_instance.get(User.account == account and User.pwd == pwd)
        except Exception as err:
            # err.message
            user = None
        return user

    # 从配置文件中添加默认账号
    @staticmethod
    def createdDefaultAccount():
        configInstance = configObj.configuration
        default_account = configInstance.get("super_user", "default_account")
        default_pwd = configInstance.get("super_user", "default_pwd")
        user = User.getUserByAccountAndPwd(default_account, default_pwd)
        if user is not None:
            return
            pass
        row = {
            "account": default_account,
            "pwd": default_pwd,
            "pwd_hash": default_pwd,
            "created_time": commonUtil.getNowStr()
        }
        User.insert(row).execute()
        pass

# 微尘
class Dust(BaseModel):
    id = IntegerField(primary_key=True)
    unique_id = CharField(verbose_name='唯一编号', max_length=200)
    interface_name = CharField(null=True, verbose_name='接口', max_length=200)
    power_type = CharField(null=True, verbose_name='电源类型', max_length=200)
    config_id = CharField(null=True, verbose_name='所使用的配置文件编号', max_length=200)
    config_name = CharField(null=True, verbose_name='所使用的配置文件名称', max_length=200)
    collect_cycle = IntegerField(verbose_name='采集周期', default=60)
    is_used = BooleanField(verbose_name='是否启用', default=True)
    pass

# 文件管理
# type "sensor"：传感数据文件 || "iot"：iot配置文件 || "dust"：微尘配置文件
class FileManager(BaseModel):
    id = IntegerField(primary_key=True)
    name = CharField(verbose_name='文件名称', max_length=200, default="")
    suffix = CharField(verbose_name='后缀', max_length=200, default="txt")
    full_name = CharField(verbose_name='全程全称（带后缀）', max_length=200, default="")
    size = IntegerField(null=True, verbose_name='后缀', default=0)
    type = CharField(verbose_name='文件类型', max_length=50, default="sensor")
    rel_id = IntegerField(null=True, verbose_name='关联的使用id')
    created_time = IntegerField(verbose_name='创建时间,时间戳便于传输', default=commonUtil.getNowUnix())
    pass


# 传感器信息表
class Sensor(BaseModel):
    id = IntegerField(primary_key=True)
    dust_id = IntegerField(verbose_name='关联的微尘序列号', default='')
    sensor_no = CharField(verbose_name='传感器序列号', max_length=200, default='')
    sensor_name = CharField(verbose_name='传感器名称', max_length=200, default='')
    type = CharField(verbose_name='传感器类型', max_length=200, default='')
    unit = IntegerField(verbose_name='传感器单位', default=60)
    job_time = IntegerField(verbose_name='定时任务周期', default=60)
    rel_equ = CharField(verbose_name='关联设备名称', max_length=200)
    max_limit = CharField(verbose_name='上限值', max_length=200, default='')
    min_limit = CharField(verbose_name='下限值', max_length=200, default='')
    is_used = BooleanField(verbose_name='是否启用', default=True)


# 传感器数据采集表
class SensorData(BaseModel):
    id = IntegerField(primary_key=True)
    sensor_no = CharField(verbose_name='传感器序列号', max_length=50, default='')
    param_name = CharField(null=True, verbose_name='采集参数名称', max_length=50, default='')
    val = CharField(null=True, verbose_name='采集值', max_length=50, default='')
    created_time = IntegerField(verbose_name='创建时间,时间戳便于传输', default=commonUtil.getNowUnix())
    is_post = BooleanField(verbose_name='是否已推送', default=False)
    # timestamp = IntegerField(verbose_name='时间戳毫秒级别', default=commonUtil.getNowUnix())

# mqtt数据记录
class MqttMessage(BaseModel):
    id = IntegerField(primary_key=True)
    uniqueId = IntegerField(null=True, verbose_name='唯一编号')
    message = TextField(null=True, verbose_name='正文数据')
    type = IntegerField(null=False, verbose_name='记录类型，0 接受的数据 || 1：发送的数据', default=0)
    is_used = BooleanField(verbose_name='是否已经使用', default=False)
    pass

# 系统运行监控数据
class SystemInfo(BaseModel):
    id = IntegerField(primary_key=True)
    cpu_usage = FloatField(verbose_name='CPU使用率')
    ram_usage = FloatField(verbose_name='内存使用率')
    collect_time = CharField(verbose_name='采集时间', max_length=50, default=commonUtil.getNowUnix())

# 服务端的命令
class RemoteCommand(BaseModel):
    id = IntegerField(primary_key=True)
    json_text = CharField(verbose_name='json字符串', default='')
    created_time = CharField(verbose_name='获取时间', max_length=50)
    is_executed = BooleanField(verbose_name='是否已被执行', default=False)

# 数据推送服务中断/重启记录表
class ServiceInterruptedRecord(BaseModel):
    id = IntegerField(primary_key=True)
    created_time = CharField(verbose_name='获取时间', max_length=50)
    remote_ip = CharField(verbose_name='当前推送ip', default="")
    last_msg = CharField(verbose_name='最后返回的数据,错误信息或者返回的传感器数据偏移量', default="")
    status = BooleanField(verbose_name='记录标记位 true：启动，false：中断', default=True)
    pass

# 分界线



@login_manager.user_loader
def load_user(user_id):
    return User.get(id=user_id)

